package com.yy.yunpan.user.controller;

import com.yy.yunpan.common.result.Result;
import com.yy.yunpan.common.util.JwtUtil;
import com.yy.yunpan.user.entity.User;
import com.yy.yunpan.user.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 *
 * @author YY
 * @since 2025-10-01
 */
@Tag(name = "用户管理", description = "用户注册、登录、信息管理相关接口")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    @Operation(summary = "用户注册", description = "用户邮箱注册")
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String password = request.get("password");
        String nickname = request.get("nickname");
        String verifyCode = request.get("verifyCode");

        User user = userService.register(email, password, nickname, verifyCode);

        Map<String, Object> result = new HashMap<>();
        result.put("userId", user.getId());
        result.put("email", user.getEmail());
        result.put("nickname", user.getNickname());

        return Result.success("注册成功", result);
    }

    @Operation(summary = "用户登录", description = "用户登录")
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String password = request.get("password");

        User user = userService.login(email, password);

        // 生成JWT Token
        String token = jwtUtil.generateToken(user.getId(), user.getEmail());

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("email", user.getEmail());
        userInfo.put("nickname", user.getNickname());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("storageQuota", user.getStorageQuota());
        userInfo.put("usedStorage", user.getUsedStorage());

        result.put("user", userInfo);

        return Result.success("登录成功", result);
    }

    @Operation(summary = "发送验证码", description = "发送邮箱验证码")
    @PostMapping("/send-verify-code")
    public Result<?> sendVerifyCode(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String type = request.get("type");

        userService.sendVerifyCode(email, type);

        return Result.success("验证码发送成功", null);
    }

    @Operation(summary = "获取用户信息", description = "根据Token获取当前用户信息")
    @GetMapping("/info")
    public Result<Map<String, Object>> getUserInfo(@RequestHeader("Authorization") String token) {
        // 解析Token
        String actualToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Long userId = jwtUtil.getUserIdFromToken(actualToken);

        User user = userService.getUserById(userId);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("email", user.getEmail());
        userInfo.put("nickname", user.getNickname());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("storageQuota", user.getStorageQuota());
        userInfo.put("usedStorage", user.getUsedStorage());
        userInfo.put("memberType", user.getMemberType());

        return Result.success(userInfo);
    }

    @Operation(summary = "更新用户信息", description = "更新用户基本信息")
    @PutMapping("/info")
    public Result<Map<String, Object>> updateUserInfo(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, String> request) {

        // 解析Token
        String actualToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Long userId = jwtUtil.getUserIdFromToken(actualToken);

        User user = userService.getUserById(userId);

        // 更新信息
        if (request.containsKey("nickname")) {
            user.setNickname(request.get("nickname"));
        }
        if (request.containsKey("avatar")) {
            user.setAvatar(request.get("avatar"));
        }

        user = userService.updateUser(user);

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("email", user.getEmail());
        userInfo.put("nickname", user.getNickname());
        userInfo.put("avatar", user.getAvatar());

        return Result.success("更新成功", userInfo);
    }

    @Operation(summary = "修改密码", description = "修改用户密码")
    @PostMapping("/change-password")
    public Result<?> changePassword(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, String> request) {

        // 解析Token
        String actualToken = token.startsWith("Bearer ") ? token.substring(7) : token;
        Long userId = jwtUtil.getUserIdFromToken(actualToken);

        String oldPassword = request.get("oldPassword");
        String newPassword = request.get("newPassword");

        userService.changePassword(userId, oldPassword, newPassword);

        return Result.success("密码修改成功", null);
    }

    @Operation(summary = "重置密码", description = "通过验证码重置密码")
    @PostMapping("/reset-password")
    public Result<?> resetPassword(@RequestBody Map<String, String> request) {
        String email = request.get("email");
        String newPassword = request.get("newPassword");
        String verifyCode = request.get("verifyCode");

        userService.resetPassword(email, newPassword, verifyCode);

        return Result.success("密码重置成功", null);
    }

    @Operation(summary = "用户登出", description = "用户退出登录")
    @PostMapping("/logout")
    public Result<?> logout() {
        // JWT是无状态的，客户端直接删除token即可
        // 如果需要服务端控制，可以将token加入黑名单
        return Result.success("退出成功", null);
    }
}